package net.zigin.nhi.could.waste.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import net.zigin.commons.util.AssertUtil;
import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.ReflectUtil;
import net.zigin.commons.util.StringUtil;
import net.zigin.nhi.could.waste.aop.LoginAspect;
import net.zigin.nhi.could.waste.exception.EpiCloudException;
import net.zigin.nhi.could.waste.vo.TokenInfoBo;
import net.zigin.nhi.could.waste.dao.*;
import net.zigin.nhi.could.waste.dto.DeviceBaseDto;
import net.zigin.nhi.could.waste.util.ExcelUtil;
import net.zigin.nhi.could.waste.vo.DeviceBaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.zigin.nhi.could.waste.model.DeviceBase;
import net.zigin.nhi.could.waste.service.DeviceBaseService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*#################################################################*
# 说明:以下代码通过哲勤代码生成工具自动生成    
# 工具:GeneratorCode
# 作者:mgw1986                                                  
# 生成时间:2021-9-12 17:47:14                                               
##################################################################*/


/**
 * DeviceBase服务实现类
 *
 * @author mgw1986
 * @version V1.0
 * @ClassName: DeviceBaseServiceImpl
 * @date 2021-9-12 17:47:14
 */
@Service
public class DeviceBaseServiceImpl extends AbstractServiceImpl<DeviceBase, String> implements DeviceBaseService {
    @Autowired
    private DeviceBaseMapper deviceBaseMapper;
    @Autowired
    private SysUserHospitalMapper sysUserHospitalMapper;
    @Autowired
    private HospitalDepartMapper hospitalDepartMapper;
    @Autowired
    private DeviceClassifyMapper deviceClassifyMapper;

    @Override
    public BaseMapper<DeviceBase, String> getMapper() {
        return deviceBaseMapper;
    }

    @Override
    public String saveOrUpdate(DeviceBaseDto deviceBaseDto) {
        AssertUtil.isNull(deviceBaseDto, "");
        TokenInfoBo tokenInfo = LoginAspect.getTokenInfo();
        deviceBaseDto.setHospitalBaseId(sysUserHospitalMapper.getHospitalBaseIdBySysUserId(tokenInfo.getUserId()));
        if (StringUtil.isNullOrEmpty(deviceBaseDto.getId())) {
            AssertUtil.isNull(deviceBaseDto.getName(), "");
            AssertUtil.isNull(deviceBaseDto.getCode(), "");
            AssertUtil.isNull(deviceBaseDto.getDeviceClassifyId(), "");
            AssertUtil.isNull(deviceBaseDto.getHospitalDepartId(), "");
            deviceBaseDto.setId(StringUtil.get32UUID());
            deviceBaseDto.setCreateUser(tokenInfo.getLoginName());
            deviceBaseDto.setCreateTime(new Date());
            deviceBaseDto.setModifyTime(new Date());
            if (StringUtil.isNullOrEmpty(deviceBaseDto.getStatus())) {
                deviceBaseDto.setStatus("unused");// 新建的设备默认未启用
            }
            DeviceBase deviceBase = ReflectUtil.copyProperties(deviceBaseDto, DeviceBase.class);
            deviceBaseMapper.insert(deviceBase);
            return deviceBase.getId();
        } else {
            deviceBaseDto.setModifyUser(tokenInfo.getLoginName());
            deviceBaseDto.setModifyTime(new Date());
            if (deviceBaseDto.getStatus().equals("normal")) {
                deviceBaseDto.setUseDate(new Date());
            }
            DeviceBase deviceBase = ReflectUtil.copyProperties(deviceBaseDto, DeviceBase.class);
            deviceBaseMapper.updateByPrimaryKeySelective(deviceBase);
            return deviceBase.getId();
        }
    }

    @Override
    public List<DeviceBaseVo> getList(DeviceBaseDto deviceBaseDto) {
        Map<String, Object> paramMap = getDeviceBaseParam(deviceBaseDto);
        return deviceBaseMapper.getInfoPageByCondition(paramMap);
    }

    @Override
    public Integer getCount(DeviceBaseDto deviceBaseDto) {
        Map<String, Object> paramMap = getDeviceBaseParam(deviceBaseDto);
        return deviceBaseMapper.getCountByCondition(paramMap);
    }

    @Override
    public DeviceBaseVo getInfoById(String id) {
        return deviceBaseMapper.getInfoById(id);
    }

    @Override
    public void exportList(DeviceBaseDto deviceBaseDto, HttpServletResponse response) {
        TokenInfoBo tokenInfo = LoginAspect.getTokenInfo();
        String hospitalBaseId = sysUserHospitalMapper.getHospitalBaseIdBySysUserId(tokenInfo.getUserId());
        List<DeviceBaseVo> list = deviceBaseMapper.getListByIds(deviceBaseDto.getIds(), hospitalBaseId);
        try {
            // 不带标题
            ExcelUtil.exportExcel(list, DeviceBaseVo.class, "设备信息", new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        try {
            ExcelUtil.exportExcel(new ArrayList<>(), DeviceBaseVo.class, "设备信息", new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importList(MultipartFile file) {
        TokenInfoBo tokenInfo = LoginAspect.getTokenInfo();
        String hospitalBaseId = sysUserHospitalMapper.getHospitalBaseIdBySysUserId(tokenInfo.getUserId());
        try {
            List<DeviceBaseVo> deviceBaseVos = ExcelUtil.importExcel(file, 0, 1, DeviceBaseVo.class);
            // 新建 todo 科室 责任人 分类 医院（通过登录人获取） 创建时间 创建人
            deviceBaseVos.forEach(deviceBaseVo -> {
                DeviceBase deviceBase = ReflectUtil.copyProperties(deviceBaseVo, DeviceBase.class);
                deviceBase.setId(StringUtil.get32UUID());
                deviceBase.setCreateTime(new Date());
                deviceBase.setCreateUser(tokenInfo.getLoginName());
                deviceBase.setHospitalBaseId(hospitalBaseId);
                if (!StringUtil.isNullOrEmpty(deviceBaseVo.getDeviceClassifyName())) {
                    String classifyId = deviceClassifyMapper.getIdByName(deviceBaseVo.getDeviceClassifyName(), hospitalBaseId);
                    if (StringUtil.isNullOrEmpty(classifyId)) {
                        throw new EpiCloudException(deviceBaseVo.getDeviceClassifyName() + ",设备分类不存在！");
                    }
                    deviceBase.setDeviceClassifyId(classifyId);
                }
                if (!StringUtil.isNullOrEmpty(deviceBaseVo.getUserStaffName())) {
                    String userStaffId = sysUserHospitalMapper.getIdByName(deviceBaseVo.getUserStaffName(), hospitalBaseId);
                    if (StringUtil.isNullOrEmpty(userStaffId)) {
                        throw new EpiCloudException(deviceBaseVo.getUserStaffName() + ",员工不存在！");
                    }
                    deviceBase.setUserStaffId(userStaffId);
                }
                if (!StringUtil.isNullOrEmpty(deviceBaseVo.getHospitalDepartName())) {
                    String departId = hospitalDepartMapper.getIdByName(deviceBaseVo.getHospitalDepartName(), hospitalBaseId);
                    if (StringUtil.isNullOrEmpty(departId)) {
                        throw new EpiCloudException(deviceBaseVo.getHospitalDepartName() + ",科室不存在！");
                    }
                    deviceBase.setHospitalDepartId(departId);
                }
                deviceBaseMapper.insert(deviceBase);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> getDeviceBaseParam(DeviceBaseDto deviceBaseDto) {
        TokenInfoBo tokenInfo = LoginAspect.getTokenInfo();
        deviceBaseDto.setHospitalBaseId(sysUserHospitalMapper.getHospitalBaseIdBySysUserId(tokenInfo.getUserId()));
        return ParamsMapUtil.getInstance()
                .addParam("keyWord", deviceBaseDto.getKeyWord())
                .addParam("hospitalBaseId", deviceBaseDto.getHospitalBaseId())
                .addParam("userStaffId", deviceBaseDto.getUserStaffId())
                .addParam("deviceClassifyId", deviceBaseDto.getDeviceClassifyId())
                .addParam("hospitalDepartId", deviceBaseDto.getHospitalDepartId())
                .addParam("model", deviceBaseDto.getModel())
                .addParam("status", deviceBaseDto.getStatus())
                .addParam("name", deviceBaseDto.getName())
                .addParam("code", deviceBaseDto.getCode())
                .addParam("pageSize", deviceBaseDto.getPageSize())
                .addParam("pageIndex", deviceBaseDto.getPageIndex());
    }
}